package com.yunwushanhe.document.utils;

public class ChainStack<T> {
    private int size = 0;
    private Node node;
    private Node top;

    /**
     * 判断栈是否为空
     * @return
     */
    public boolean empty(){
        if(size == 0){
            return true;
        } else {
            return false;
        }
    }

    /**
     * 把数据放入栈节点并压入栈
     * @param data
     */
    public void push(T data){
        if(size == 0){
            node = new Node(data,null);
            top = node;
            ++size;
        } else {
            node = new Node(data,top);
            top = node;
            ++size;
        }
    }

    /**
     * 查看栈顶的数据
     * @return
     */
    public T peek(){
        if(empty()){
            throw new IllegalArgumentException("该栈为空，栈顶没有元素可以查看！");
        }
        return top.data;
    }

    /**
     * 移除栈顶的数据，并可以查看
     * @return
     */
    public T pop(){
        if(empty()){
            throw new IllegalArgumentException("该栈为空，栈顶没有元素可以取出并移除！");
        } else {
            T element;
            element = top.data;
            node = top;
            top = top.next;
            node.next = null;
            --size;
            return element;
        }
    }

    /**
     * 获得栈中有多少个节点数据
     * @return
     */
    public int getSize(){
        return size;
    }


    /**
     * 栈节点
     */
    class Node{
        private T data;
        private Node next;

        public Node(T data, Node next) {
            this.data = data;
            this.next = next;
        }
    }
}
